// ignore_for_file: unused_local_variable, constant_identifier_names, depend_on_referenced_packages

import 'dart:async';
import 'dart:isolate';
import 'dart:io';
import 'dart:ui';
import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart';

const int SPIF_UPDATEINIFILE = 0x01;
const int SPIF_SENDCHANGE = 0x02;

class WallpaperService {
  // 设置Windows桌面壁纸
  // [imagePath] 图片的完整路径
  static Future<bool> setWallpaperInIsolate(String imagePath) async {
    final receivePort = ReceivePort();
    Isolate.spawn(_setWallpaper, imagePath).then((isolate) {
      return true;
    }).catchError((error) {
      return false;
    });
    return true;
  }

  static void _setWallpaper(String imagePath) {
    try {
      final file = File(imagePath);
      if (!file.existsSync()) {
        return;
      }

      final pathPointer = imagePath.toNativeUtf16();

      final result = SystemParametersInfo(
        SPI_SETDESKWALLPAPER,
        0,
        pathPointer,
        SPIF_UPDATEINIFILE | SPIF_SENDCHANGE,
      );

      free(pathPointer);

      if (result != 0) {
        // 通过 SendPort 发送消息到主 UI 线程
        final sendPort = IsolateNameServer.lookupPortByName('mainPort');
        sendPort?.send({'code': 200, 'message': '设置成功'});
      } else {
        final sendPort = IsolateNameServer.lookupPortByName('mainPort');
        sendPort?.send({'code': 400, 'message': '设置失败'});
      }
    } catch (e) {
      final sendPort = IsolateNameServer.lookupPortByName('mainPort');
      sendPort?.send({'code': 400, 'message': '设置失败: $e'});
    }
  }
}
